/*
 *  Copyright 2011 yura.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.vcforms.bean;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.opu.vcforms.io.Logger;
import org.opu.vcforms.template.TxtTemplate;

/**
 *
 * @author yura
 */
public class Template {

    private String name;
    // Document is old variand
//    private Document parsed = null;
    private TxtTemplate parsed = null;

    public Template(String name, byte[] data) {
        this.name = name;
        this.parsed = parseData(data);
    }

    public String getName() {
        return name;
    }

    public TxtTemplate getTemplate(){
        return parsed;
    }

    /**
     * To change behaviors overwrite method {@link #initData(String) }
     */
    public final TxtTemplate parseData(byte[] data){
        try {
            return initData(data);
        } catch (IOException ex) {
            Logger.error("Can't to parse data from database: " + ex);
            try {
                Logger.infor(new String(data, "UTF-8"));
            } catch (UnsupportedEncodingException ex1) {
                Logger.error("The template in the wrong encoding: " + ex1);
            }
            return null;
        }
    }

    protected TxtTemplate initData(byte[] data) throws IOException{
//            return new DefaultDocumentReader().parseDocument(new StringReader(data));
        TxtTemplate txtTemplate = new TxtTemplate();
        txtTemplate.load(new ByteArrayInputStream(data));
        return txtTemplate;
    }

    @Override
    public String toString() {
        return String.valueOf(name);
    }

}
